JavaScript Async/Await Examples

Example 1: Basic Async/Await

This example demonstrates a basic async function that fetches a message after a delay of 2 seconds.


<!DOCTYPE html>
<html>
<body>
    <p>This will show the result after a 2-second delay:</p>
    <div id="example1-output"></div>
    <script>                        
        async function basicAsyncFunction() {
            let promise = new Promise((resolve) => {
                setTimeout(() => resolve("Data loaded after 2 seconds"), 2000);
            });
            let result = await promise;
            document.getElementById("example1-output").innerText = result;
        }
        basicAsyncFunction();
    </script>
</body>
</html>
        
Result will appear here...

Example 2: Async/Await with Error Handling

In this example, we simulate an error in an async function and handle it using try...catch.


<!DOCTYPE html>
<html>
<body>
    <div id="example2-output"></div>
    <script>                        
    async function asyncWithErrorHandling() {
        try {
            let promise = new Promise((resolve, reject) => {
                setTimeout(() => reject("An error occurred!"), 2000);
            });
            let result = await promise;
            document.getElementById("example2-output").innerText = result;
        } catch (error) {
            document.getElementById("example2-output").innerText = error;
        }
    }
    asyncWithErrorHandling();
    </script>
</body>
</html>
        
Result will appear here...

Example 3: Fetching Data from an API

This example uses the fetch API to retrieve JSON data from a public API using async/await.


<!DOCTYPE html>
<html>
<body>
    <div id="example3-output"></div>
    <script>                        
        async function fetchDataFromAPI() {
            try {
                let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
                let data = await response.json();
                document.getElementById("example3-output").innerText = `Title: ${data.title}`;
            } catch (error) {
                document.getElementById("example3-output").innerText = "Error fetching data.";
            }
        }
        fetchDataFromAPI();
    </script>
</body>
</html>
        
Fetching data...